package com.changhong.wlyspectrum.MainTestActivity;

import android.app.Activity;
import android.app.PendingIntent;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.Attributes;
import com.changhong.wlyspectrum.utils.ConnectDialog;
import com.changhong.wlyspectrum.utils.Detail;
import com.changhong.wlyspectrum.utils.MetaDataBean;
import com.changhong.wlyspectrum.utils.MyConfig;
import com.changhong.wlyspectrum.utils.SampleInfo;
import com.google.gson.Gson;
import com.squareup.okhttp.Response;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by Mr_tao
 * on 2017/3/9.
 */

public class TestResultActivity extends Activity{    //样本扫描，画图
    private static final String TAG = "TestResultActivity";
    private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
    private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
    private XYSeries mCurrentSeries;
    private XYSeriesRenderer mCurrentRenderer;
    private GraphicalView mChartView;

    // 设备列表
    private HashMap<String, UsbDevice> deviceList;
    // USB管理器:负责管理USB设备的类
    private UsbManager manager;
    // 找到的USB设备
    private UsbDevice mUsbDevice;
    // 代表USB设备的一个接口
    private UsbInterface mInterface;
    private UsbDeviceConnection mDeviceConnection;
    // 代表一个接口的某个节点的类:写数据节点
    private UsbEndpoint usbEpOut;
    // 代表一个接口的某个节点的类:读数据节点
    private UsbEndpoint usbEpIn;
    // 要发送信息字节
    private byte[] sendbytes;
    // 接收到的信息字节
    private byte[] receiveytes;
    private PendingIntent mPermissionIntent;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private static final String ACTION_USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    private static final String ACTION_USB_DEVICE_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
    private boolean HasUsb = false;

    private Button mScanBtn;
    private ImageView mBackIv;
    private String mWet;
    private String mStarch;
    private String mAcidity;
    private String mSugar;
    private int count = 0;
    private double Temp = 0;
    private double[] mPoint = new double[100];
    private double[][] mData = new double[100][2];    //实测光谱
    private double[][] mData0 = new double[100][2];
    private double[][] mData1 = new double[100][2];    //基本光谱
    private double[][] mData2 = new double[100][2];
    private double[][] mData3 = new double[100][2];
    private double[] mResult = new double[100];
    private double Ymean = 0;
    private double delta = 0;
    private String user_id;
    private String device_id;
    private String token;
    private String kuahao;
    private String paihao;
    private String yaohao;
    private String cengci;
    private String churu;
    private int color = 0;
    private int[] mColor= new int[]{Color.RED,Color.BLUE,Color.BLACK,Color.GREEN, Color.YELLOW};
    private int flag = -1;
    private double k = 0;
    private double r = 0;
    private String collectionId;
    private String name;
    private String description;
    private HashMap<String,String> hashMap = new HashMap<String,String>();

    private BluetoothGatt mBluetoothGatt;
    private BluetoothGattService service;
    private BluetoothGattCharacteristic characteristic_read;
    private BluetoothGattCharacteristic characteristic_write;
    private String uuidservice =     "0000b350-d6d8-c7ec-bdf0-eab1bfc6bcbc";
    private String uuidchara_read =  "0000b351-d6d8-c7ec-bdf0-eab1bfc6bcbc";   //read
    private String uuidchara_write = "0000b352-d6d8-c7ec-bdf0-eab1bfc6bcbc";  //write
    private int numData = 0;
    private BluetoothDevice mdevice;

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mDataset = (XYMultipleSeriesDataset) savedInstanceState.getSerializable("dataset");
        mRenderer = (XYMultipleSeriesRenderer) savedInstanceState.getSerializable("renderer");
        mCurrentSeries = (XYSeries) savedInstanceState.getSerializable("current_series");
        mCurrentRenderer = (XYSeriesRenderer) savedInstanceState.getSerializable("current_renderer");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("dataset", mDataset);
        outState.putSerializable("renderer", mRenderer);
        outState.putSerializable("current_series", mCurrentSeries);
        outState.putSerializable("current_renderer", mCurrentRenderer);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_result_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_test_result);

        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        InitData();
        InitView();
        InitUi();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(mReceiver, filter);

        //mData0 = MainTestActivity.mData0;
        mData1 = MainTestActivity.mData1;
        for(int i=0;i<mData1.length;i++){
            Log.e("wydong","wydong..... mData1:"+mData1[i][1]);
        }
        if (mChartView == null) {
            LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
            mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);
            // enable the chart click events
            mRenderer.setClickEnabled(true);
            mRenderer.setSelectableBuffer(10);
            mChartView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // handle the click event on the chart
                    SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
                    if (seriesSelection == null) {
                        // Toast.makeText(XYChartBuilder.this, "No chart
                        // element", Toast.LENGTH_SHORT).show();
                    } else {
                        // display information of the clicked point
                        Toast.makeText(TestResultActivity.this,
                                "Chart element in series index " + seriesSelection.getSeriesIndex()
                                        + " data point index " + seriesSelection.getPointIndex() + " was clicked"
                                        + " closest point value X=" + seriesSelection.getXValue() + ", Y="
                                        + seriesSelection.getValue(),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
            layout.addView(mChartView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
            boolean enabled = mDataset.getSeriesCount() > 0;
            // setSeriesWidgetsEnabled(enabled);
        } else {
            mChartView.repaint();
        }

        InitXY();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
        if(mBluetoothGatt!=null){
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
        }
    }

    private void InitData(){
        Intent intent = getIntent();
        /*mWet = intent.getStringExtra("wet");
        mStarch = intent.getStringExtra("starch");
        mAcidity = intent.getStringExtra("acidity");
        mSugar = intent.getStringExtra("sugar");*/
        hashMap =(HashMap<String,String>) intent.getSerializableExtra("hashmap");
        collectionId = intent.getStringExtra("collectionId");
        //Log.e(TAG, "wet:" + mWet + "starch:" + mStarch + "acidity:" + mAcidity + "sugar:" + mSugar);
        Log.e(TAG,"collectionId----->" + collectionId);

        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        user_id = mypref.getString("user_id", "default");
        token = mypref.getString("token", "default");
        kuahao = mypref.getString("kuahao", "");
        paihao = mypref.getString("paihao", "");
        yaohao = mypref.getString("yaohao", "");
        cengci = mypref.getString("cengci", "");
        churu = mypref.getString("churu", "");

        GetCollectiodById();
    }

    private void InitView(){
        // set some properties on the main renderer
        mRenderer.setApplyBackgroundColor(true);
        mRenderer.setBackgroundColor(getResources().getColor(R.color.white));
        mRenderer.setAxisTitleTextSize(25);
        mRenderer.setChartTitleTextSize(20);
        mRenderer.setLabelsTextSize(20);
        mRenderer.setXTitle(getString(R.string.x_title));
        mRenderer.setYTitle(getString(R.string.y_title));
        mRenderer.setLabelsColor(Color.BLACK);
       // mRenderer.setFitLegend(true);
       // mRenderer.setLegendTextSize(15);
        mRenderer.setYLabelsPadding(5);
        // mRenderer.setYAxisAlign(Align.RIGHT,0);
        mRenderer.setMargins(new int[] { 20, 60, 15, 0 });
        mRenderer.setZoomButtonsVisible(false);
        mRenderer.setPointSize(5);
        mRenderer.setShowLegend(false);
        mRenderer.setMarginsColor(Color.WHITE);
        mRenderer.setYLabelsColor(0, Color.BLACK);
        mRenderer.setXLabelsColor(Color.BLACK);
        mRenderer.setAxesColor(Color.BLACK);
        mRenderer.setYLabelsAlign(Paint.Align.RIGHT);
        //mRenderer.setZoomEnabled(false, true);
        mRenderer.setPanLimits(new double[] { 1550, 1860, 0, 1 });
        mRenderer.setZoomLimits(new double[] { 1550, 1860, 0, 1 });
    }
    private void InitUi(){
        mBackIv = (ImageView) findViewById(R.id.test2wuliangye);
        mBackIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mScanBtn = (Button)findViewById(R.id.add);
        mScanBtn.setEnabled(true);
        mScanBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if(!MainTestActivity.IsAdjusted){
                    //Log.e(TAG,mData0[0][1]);
                    Log.e(TAG,MainTestActivity.IsAdjusted + "");
                    Toast.makeText(getApplicationContext(), R.string.adjust_first, Toast.LENGTH_SHORT).show();
                    return;
                }
                flag = 0;
                mScanBtn.setEnabled(false);
                mScanBtn.setText(R.string.is_scanning);
                Log.e("wydong","wydong getModeStatus:"+MyConfig.getModeStatus());
                if(MyConfig.getModeStatus()){  //蓝牙
                    Log.e("wydong","wydong mdevice:"+mdevice);
                    if(mdevice==null){
                        mdevice  = MyConfig.getBluetoothDevice();
                        mBluetoothGatt = mdevice.connectGatt(TestResultActivity.this, false, mGattCallback1);
                    }else{
                        myHandler.sendMessage(Message.obtain(myHandler, 100));
                    }
                }else{        //usb
                    boolean ableusb = InitUsb();
                    if(ableusb){
                        Intent mIntent1 = new Intent(ACTION_USB_PERMISSION);
                        mPermissionIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mIntent1, 0);
                        manager.requestPermission(mUsbDevice, mPermissionIntent);
                    }else{
                        myHandler.sendMessage(Message.obtain(myHandler, 5));
                    };
                }
                InitXY();
                if(color < 4){
                    color++;
                }else{
                    color = 0;
                }
            }
        });
    }

    private  void writeOrder(final byte[] bytes){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    characteristic_write.setValue(bytes);
                    //设置回复形式
                    characteristic_write.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                    //开始写数据
                    mBluetoothGatt.writeCharacteristic(characteristic_write);
                    mBluetoothGatt.setCharacteristicNotification(characteristic_read,true);
                } catch (Exception e) {
                    Log.e("Write", e.toString());
                }
            }
        });
        thread.start();

    }
    private void InitXY() {
        String seriesTitle = getResources().getString(R.string.line_name) + (mDataset.getSeriesCount() + 1);
        // create a new series of data
        XYSeries series = new XYSeries(seriesTitle);
        mDataset.addSeries(series);
        mCurrentSeries = series;
        // create a new renderer for the new series
        XYSeriesRenderer renderer = new XYSeriesRenderer();
        mRenderer.addSeriesRenderer(renderer);
        // set some renderer properties
        renderer.setPointStyle(PointStyle.POINT);
        renderer.setFillPoints(true);
        renderer.setDisplayChartValues(false);
        renderer.setDisplayChartValuesDistance(10);
        renderer.setColor(mColor[color]);
        ///

        ///
        mCurrentRenderer = renderer;
        // setSeriesWidgetsEnabled(true);
        mChartView.repaint();
    }

    private boolean InitUsb() {
        //find device
        if(manager == null){
            return false;
        }
        deviceList = manager.getDeviceList();
        if(deviceList.isEmpty()){
            return false;
        }
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            UsbDevice usb = deviceIterator.next();
            int vendorId = usb.getVendorId();
            int productId = usb.getProductId();
            Log.e("ldm", "vid=" + vendorId + "---pid=" + productId);
            if(productId==22352){
                mUsbDevice = usb;
            }
        }
        if (mUsbDevice == null) {
            ConnectDialog.dismiss();
            return false;
        }
        //find interface
        Log.e(TAG, "InitUsb mUsbDevice.getInterfaceCount():"+mUsbDevice.getInterfaceCount());
        for (int i = 0; i < mUsbDevice.getInterfaceCount();) {
            UsbInterface usbInterface = mUsbDevice.getInterface(i);
            mInterface = usbInterface;
            break;
        }
        if(mInterface == null){
            return false;
        }
        //find endpoint
        Log.e(TAG, "InitUsb ------："+mInterface.getEndpointCount());
        for (int i = 0; i < mInterface.getEndpointCount(); i++) {
            UsbEndpoint ep = mInterface.getEndpoint(i);
            // look for interrupte endpoint
            if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                    usbEpOut = ep;
                }
                if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                    usbEpIn = ep;
                }
            }
        }
        if (usbEpOut != null && usbEpIn != null) {
            return true;
        } else {
            return false;
        }
    }

    private void SetXY(double X, double Y) {
        double x = 0;
        double y = 0;
        try {
            x = X;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        try {
            y = Y;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        mCurrentSeries.add(x, y);
        mChartView.repaint();
    }

    /**
     * 读取扫描值
     * @param buffer
     * @param length
     * @param Data
     */
    private boolean readDectFromUsb(byte[] buffer, int length,double[][] Data) {
        boolean flag = false;
        if (mDeviceConnection != null) {
            try{
                if (mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000)>0) {
                    int num = 0;
                    while (true) {
                        receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                        int len = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 2000);
                        //Log.e(TAG, "receive len----->" + len);
                        if (len > 0) {
                            Log.e(TAG, "receive" + "[" + num + "]"+len);
                            int[] data = {byteToint1(receiveytes[9], receiveytes[8]),
                                    byteToint1(receiveytes[5], receiveytes[4])};
                            Data[num][0] = data[0];
                            Data[num][1] = data[1];
                            num++;
                        } else {
                            break;
                        }
                    }
                    if(num==100){   // 必须获取100个数就算完成
                        flag = true;
                    }
                }

            }catch (Exception e){
                return false;
            }
        }
        return  flag;
    }
    /**
     * 读取温度
     * @param buffer
     * @param length
     */
    private void TsendToUsb(byte[] buffer, int length){
        if (mDeviceConnection != null) {
            int ret = -1;
            if (mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000)>0) {
                while (true) {
                    receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                    ret = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 1500);
                    if (ret <0) {
                        break;
                    }
                   /* for (int i = 0; i < ret; i++) {
                        Log.e(TAG, "receve" + i + ":0x" + String.format("%2x", receiveytes[i]).toUpperCase());
                    }*/
                    int mtemp = byteToint1(receiveytes[5], receiveytes[4]);
                    Temp= MyConfig.getTemputer(mtemp);
                    Log.e(TAG,"Temp:"+Temp);
                    myHandler.sendMessage(Message.obtain(myHandler, 4));
                }
            }
        } else {
            Toast.makeText(getApplicationContext(), R.string.device_connect_abnormal, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 读取版号
     * @param buffer
     * @param length
     */
    private void DsendToUsb(byte[] buffer, int length){
        if (mDeviceConnection != null) {
            int ret = -1;
            if (mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000)>0) {
                int j = 1;
                while (true) {
                    receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                    ret = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 1500);
                    if (ret <0) {
                        break;
                    }
                    Log.e("wydong","wydong DsendToUsb:"+receiveytes.length);
                    /*Log.e(TAG, "receive" + "[" + j++ + "]" + ret);
                    for (int i = 0; i < ret; i++) {
                        Log.e(TAG, "receve" + i + ":0x" + String.format("%2x", receiveytes[i]).toUpperCase());
                    }*/
                    device_id = byteToint2(receiveytes[7], receiveytes[6],receiveytes[5],receiveytes[4]) + "";
                }
                myHandler.sendMessage(Message.obtain(myHandler, 0));
            }
        } else {
            Toast.makeText(getApplicationContext(), R.string.device_connect_abnormal, Toast.LENGTH_SHORT).show();
        }
    }

    private Handler myHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            ConnectDialog.dismiss();
            switch (msg.what) {
                case 0:
                    Log.e("wydong","wydong myHandler 0");
                    mScanBtn.setText(R.string.begin_test);
                    MyConfig.bubbleSort(mData);
                    delta = 0;
                    double sum = 0;
                    //五点平滑
                    /*for(int i = 0;i < mData.length;i++){
                        if(i<=95){
                            mData[i][1] = (mData[i][1]+mData[i+1][1]+mData[i+2][1]+mData[i+3][1]+mData[i+4][1])/5;
                        }else if(i == 96){
                            mData[i][1] = (mData[i][1]+mData[i+1][1]+mData[i+2][1]+mData[i+3][1])/4;
                        }else if(i == 97){
                            mData[i][1] = (mData[i][1]+mData[i+1][1]+mData[i+2][1])/3;
                        }else if(i == 98){
                            mData[i][1] = (mData[i][1]+mData[i+1][1])/2;
                        }

                    }*/
                    MyConfig.Smoothing(mData); //七点平滑
                    //step 1
                    for(int i = 0;i < mData.length;i++){
                        //r = (mData[i][1] - mData0[i][1])/(mData1[i][1] - mData0[i][1]);
                        r = mData[i][1] /mData1[i][1];
                        mResult[i] = 1 - r;
                        sum = sum + mResult[i];
                    }
                    //step 2
                    Ymean = sum/100;
                    //step 3
                    for(int i = 0;i < mData.length;i++){
                        delta = delta + (mResult[i] - Ymean) * (mResult[i] - Ymean);
                    }
                    delta = Math.sqrt(delta);
                    Log.e(TAG, "point----->delta:" + delta+",Ymean:"+Ymean);
                    //step 4、5
                    for(int i = 0;i<mData.length;i++){
                        Log.e(TAG, "point----->mResult[i]:" + mResult[i]);
                        mResult[i] = (mResult[i] - Ymean)/delta;
                        Log.e(TAG, "point----->x:" + mData[i][0] +"y:" +  mResult[i]);
                        if(i >= 1){
                            SetXY(mData[i][0], (mResult[i] + mResult[i - 1])/2);
                        }else{
                            SetXY(mData[i][0], mResult[i]);
                        }
                    }
                    myHandler.sendMessage(Message.obtain(myHandler, 1));

                    break;
                case 1:
                    List<Double> label = new ArrayList<Double>();
                    List<Double> series = new ArrayList<Double>();
                    List<Double> noLight = new ArrayList<Double>();
                    List<Double> baseLight = new ArrayList<Double>();
                    for(int i = 0 ;i < mData.length; i++){
                        label.add(mData[i][0]);
                        series.add(mData[i][1]);
                        noLight.add(0.0);     //noLight 给为0
                        baseLight.add(mData1[i][1]);
                    }

                    /*HashMap<String,String> hashMap = new HashMap<String,String>();
                    hashMap.put("water",mWet);
                    hashMap.put("starch",mStarch);
                    hashMap.put("acidity",mAcidity);
                    hashMap.put("sugar",mSugar);*/
                    //String name = kuahao +"跨" +paihao +"排"+ yaohao +"窑" +cengci+"层" + churu;
                    MetaDataBean metadata = new MetaDataBean();
                    if(collectionId.compareTo("1") == 0){
                        metadata.setName("铁骑力士智能快检");
                        metadata.setCollect("玉米蛋白粉分析");
                    }else if(collectionId.compareTo("2") == 0){
                        metadata.setName("五粮液智能快检");
                        metadata.setCollect("酒嶆分析");
                    }else{
                        metadata.setName("智能快检");
                        metadata.setCollect("样本分析");
                    }

                    SampleInfo sampleInfo = new SampleInfo();
                    sampleInfo.setSampleType("custom");
                    sampleInfo.setStart("1550");
                    sampleInfo.setStep("1850");
                    sampleInfo.setNumber("100");
                    metadata.setSampleInfo(sampleInfo);

                    metadata.setLabel(label);
                    metadata.setSeries(series);

                    Detail detail = new Detail();
                    detail.setNoLightSeries(noLight);
                    detail.setBaseLightSeries(baseLight);
                    metadata.setDetail(detail);

                    /*Attributes attributes = new Attributes();
                    attributes.setWater(mWet + "");
                    attributes.setStarch(mStarch + "");
                    attributes.setAcidity(mAcidity + "");
                    attributes.setSugar(mSugar + "");*/
                    hashMap.put("sys_temperature",Double.toString(Temp));
                    metadata.setAttri(hashMap);
                    mScanBtn.setEnabled(true);
                    UpdateData(user_id,device_id,name,collectionId,description,"1",metadata);
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), R.string.update_success, Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(), R.string.update_fail, Toast.LENGTH_LONG).show();
                    break;
                case 4:
                    Log.e("wydong","wydong Temp:"+Temp);
                    String mstr = getResources().getString(R.string.now_temputer) + "" + Temp;
                    Toast.makeText(getApplicationContext(),mstr, Toast.LENGTH_LONG).show();
                    break;
                case 5:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.device_not_found));
                    break;
                case 6:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.no_permission));
                    break;
                case 7:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.device_disconnect));
                    break;
                case 97:
                    Toast.makeText(getApplicationContext(), "数据传输错误，请重新检测", Toast.LENGTH_SHORT).show();
                    break;
                case 98:
                    Toast.makeText(getApplicationContext(), R.string.network_error, Toast.LENGTH_LONG).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(), R.string.service_error, Toast.LENGTH_LONG).show();
                    break;
                case 100:
                    service = mBluetoothGatt.getService(UUID.fromString(uuidservice));
                    characteristic_read= service.getCharacteristic(UUID.fromString(uuidchara_read));
                    characteristic_write = service.getCharacteristic(UUID.fromString(uuidchara_write));

                    //characteristic_read= MyConfig.characteristic_read;
                    //characteristic_write = MyConfig.characteristic_write;
                    Delay(500);
                    writeOrder(MyConfig.blueReadId());
                    Delay(300);
                    writeOrder(MyConfig.blueReadTemp());
                    Delay(300);
                    writeOrder(MyConfig.blueLightOn());
                    Delay(300);
                    writeOrder(MyConfig.blueSetDetect());
                    break;

                default:
                    break;

            }
        }
    };

    public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {

        private Thread.UncaughtExceptionHandler mDefaultUEH;

        public CustomExceptionHandler() {
            Log.d(TAG, "------------ CustomExceptionHandler ------------");
            mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        }

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(TAG, "------------ uncaughtException ------------ " + ex.getMessage());

            mDefaultUEH.uncaughtException(thread, ex); // 不加本语句会导致ANR
        }

    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            String action = arg1.getAction();
            Log.e(TAG, action);
            //showTmsg(action);
            if (action.equals(ACTION_USB_PERMISSION)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice) arg1.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (arg1.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            if (manager.hasPermission(mUsbDevice)) {
                                mDeviceConnection = manager.openDevice(mUsbDevice);
                                if (mDeviceConnection == null) {
                                    return;
                                }
                                if (mDeviceConnection.claimInterface(mInterface, true)) {
                                    HasUsb = true;
                                    ConnectDialog.showDialog(TestResultActivity.this,getString(R.string.is_scanning));
                                    Log.e(TAG, "sendTousb");
                                    Send();
                                } else {
                                    mDeviceConnection.close();
                                }
                            } else {
                                myHandler.sendMessage(Message.obtain(myHandler, 6));
                            }
                        }
                    } else {
                        Log.d(TAG, "permission denied for device " + device);
                    }
                }
            } else if (action.equals(ACTION_USB_DEVICE_ATTACHED)) {
                if (!HasUsb) {
                    InitUsb();
                }
            } else if (action.equals(ACTION_USB_DEVICE_DETACHED)) {
                myHandler.sendMessage(Message.obtain(myHandler, 7));
                HasUsb = false;
            }
        }

    };

    private void UpdateData(final String userId, final String deviceId, final String name,final String collectionId,final String description, final String isSimple,final MetaDataBean metaDataBean){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String mfirmwareVersion = "USBV1.0";
                String mappVersion = "1.0";
                String msoftVersion = "1.0.1";
                String mmodelVersion = "0.0.1";
                try{
                    Gson gson = new Gson();
                    String metadata = gson.toJson(metaDataBean);
                    Log.e(TAG,metadata);
                    Response response = HttpMethods.UpdateResponse("/scio/records/add",token,userId,deviceId,name,collectionId,description,isSimple,metadata,mfirmwareVersion,mappVersion,msoftVersion,mmodelVersion);
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.compareTo("0") == 0) {
                            myHandler.sendMessage(Message.obtain(myHandler, 2));
                        } else {
                            myHandler.sendMessage(Message.obtain(myHandler, 3));
                        }
                    }else{
                        myHandler.sendMessage(Message.obtain(myHandler, 98));
                    }
                } catch (IOException e) {
                    myHandler.sendMessage(Message.obtain(myHandler, 98));
                    e.printStackTrace();
                } catch (JSONException e) {
                    myHandler.sendMessage(Message.obtain(myHandler, 98));
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void GetCollectiodById(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String path = "/collection/" + collectionId;
                try {
                    Response response = HttpMethods.TGetResponse(path,user_id,token);
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        Log.e(TAG,"code----->" + code);
                        if(code.compareTo("0") == 0){
                            JSONArray jsonArray = new JSONArray(jsonObject.getString("jsonObj"));
                            JSONObject jsonobj = new JSONObject(jsonArray.getString(0));
                            name = jsonobj.getString("name");
                            collectionId = jsonobj.getString("collectionId");
                            description = jsonobj.getString("description");
                            Log.e(TAG,name + " " + collectionId + " " + description);
                        }else{
                            myHandler.sendMessage(Message.obtain(myHandler, 99));
                        }
                    }else{
                        myHandler.sendMessage(Message.obtain(myHandler, 98));
                    }
                } catch (IOException e) {
                    myHandler.sendMessage(Message.obtain(myHandler, 98));
                    e.printStackTrace();
                }catch (JSONException e){
                    myHandler.sendMessage(Message.obtain(myHandler, 98));
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void Send(){
        Log.e(TAG, "flag----->" + flag);
        if(flag == 0){
            new Thread(new Runnable() {
                public void run() {
                    if(!readDectFromUsb(MyConfig.SetDetect(), MyConfig.SetDetect().length,mData)){
                        myHandler.sendMessage(Message.obtain(myHandler, 97));
                    }
                    Delay(60);
                   // SendToUsb(MyConfig.SetDetect(), MyConfig.SetDetect().length, mData2);
                    //Delay(100);
                    //SendToUsb(MyConfig.SetDetect(), MyConfig.SetDetect().length, mData3);
                    //Delay(100);
                    TsendToUsb(MyConfig.ReadTemp(), MyConfig.ReadTemp().length);
                    Delay(30);

                    DsendToUsb(MyConfig.ReadId(), MyConfig.ReadId().length);
                }
            }).start();


        }
    }

    private void Delay(int time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private int byteToint1(byte hbyte, byte lbyte) {
        int l = lbyte;
        l &= 0xFF;
        l |= ((int) hbyte << 8);
        l &= 0xFFFF;
        return l;
    }

    private int byteToint2(byte fbyte, byte sbyte, byte hbyte, byte lbyte) {
        int l = lbyte;
        l &= 0xFF;
        l |= ((int) hbyte << 8);
        l &= 0xFFFF;
        l |= ((int)sbyte << 16);
        l &= 0xFFFFFF;
        l |= ((int)fbyte << 24);
        l &= 0xFFFFFFFF;
        return l;
    }

    private BluetoothGattCallback mGattCallback1 = new BluetoothGattCallback() {

        //连接状态改变的回调
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                            int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功后启动服务发现
                mBluetoothGatt.discoverServices();
                Log.e(TAG, "TestResultActivity wydong 启动服务发现");
            }
        };

        //发现服务的回调
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "TestResultActivity wydong 成功发现服务");
                myHandler.sendMessage(Message.obtain(myHandler, 100));
            }else{
                Log.e(TAG, "服务发现失败，错误码为:" + status);
            }
        };

        //写操作的回调
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
               // Log.e(TAG, "写入成功:" +characteristic.getValue().length);
            }

        };

        //读操作的回调
        public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
               // Log.e(TAG, "读取成功:" +characteristic.getValue().length);
            }
        }

        //数据返回的回调（此处接收BLE设备返回数据）
        public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
            Log.e(TAG,"Changed wydong:"+characteristic.getValue().length);
            byte[] receiveytes = characteristic.getValue();
            if(receiveytes.length==12){
                    int[] data = {byteToint1(receiveytes[9], receiveytes[8]),
                            byteToint1(receiveytes[5], receiveytes[4])};
                    if(numData<100){
                        mData[numData][0] = data[0];
                        mData[numData][1] = data[1];
                        numData+=1;
                    }
                    Log.e(TAG,"Changed on分析numData:"+numData);
                    if(numData==100){
                        myHandler.sendMessage(Message.obtain(myHandler, 0));
                        numData = 0;
                    }


            }
            if(receiveytes.length==6){   //temputer
                int mtemp = byteToint1(receiveytes[5], receiveytes[4]);
                Temp = MyConfig.getTemputer(mtemp);
                Log.e(TAG,"Changed 温度:"+Temp);
            }

            if(receiveytes.length==8) { //id
                device_id = byteToint2(receiveytes[7], receiveytes[6],receiveytes[5],receiveytes[4]) + "";
            }

        };
    };
}
